﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataModels.Common;
using GenericTools;
using GenericTools.Models;

namespace ReportingManagement.Components.AutoReminder
{
    public partial class AutomaticSMSReminder : Form
    {
        #region Enumeration
        private enum DisplayLevel
        {
            BY_FACILITIES,
            BY_DISTRICTS,
            BY_REGIONS
        }
        #endregion

        #region Constants
        #region DisplayLevel
        private const string BY_FACILITIES = "FACILITIES";
        private const string BY_DISTRICTS = "DISTRICTS";
        private const string BY_REGIONS = "REGIONS";
        #endregion
        #endregion

        public AutomaticSMSReminder()
        {
            InitializeComponent();

            CreateDisplayLevelList();
            AutoReminderSettings.TryLoadingDefaultConfigurations();
            LoadAutoReminderConfigurations();

            string setting = Utilities.GetSetting(AutoReminderSettings.AUTO_REMINDER_LAST_SEND_DATE);
            DateTime reminderLastSendDate;
            if (DateTime.TryParse(setting, out reminderLastSendDate))
            {
                string sRemindingDate = string.Format("{0:ddd, dd MMM yyyy hh:mm tt}", reminderLastSendDate);
                this.Text = string.Format("{0} -  Last auto-reminder was sent on {1}", this.Text, sRemindingDate);
            }
        }       

        private void cboDisplayLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = cboDisplayLevel.SelectedItem as ListItem;
            if (item != null)
            {
                checkedListBox.Items.Clear();
                DisplayLevel displayLevel = (DisplayLevel)item.Value;
                switch (displayLevel)
                {
                    case DisplayLevel.BY_FACILITIES:
                        DataTable facilitiesDataTable = Utilities.GetAllFacilitiesStatus();
                        DataTable selectedFacilities = Utilities.GetAutoReminderConfiguredFacilities();
                        foreach (DataRow r in facilitiesDataTable.Rows)
                        {
                            string facilityCode = r["Facility Code"].ToString();
                            ListItem i = new ListItem();
                            i.Text = r["Facility Name"].ToString();
                            i.Value = facilityCode;

                            bool isChecked = false;
                            foreach (DataRow row in selectedFacilities.Rows)
                            {
                                string code = row["FacilityCode"].ToString();
                                if (code == facilityCode)
                                {
                                    isChecked = true;
                                    selectedFacilities.Rows.Remove(row);    // to reduce unnecessary iterations
                                    break;
                                }
                            }
                            checkedListBox.Items.Add(i, isChecked);
                        }
                        break;

                    case DisplayLevel.BY_DISTRICTS:
                        DataTable districtsDataTable = Utilities.GetAllDistricts();
                        DataTable selectedDistricts = Utilities.GetAutoReminderConfiguredDistricts();
                        foreach (DataRow r in districtsDataTable.Rows)
                        {
                            int districtId = int.Parse(r["DistrictNo"].ToString());
                            ListItem i = new ListItem();
                            i.Text = r["District"].ToString();
                            i.Value = districtId;

                            bool isChecked = false;
                            foreach (DataRow row in selectedDistricts.Rows)
                            {
                                int id = int.Parse(row["DistrictId"].ToString());
                                if (id == districtId)
                                {
                                    isChecked = true;
                                    selectedDistricts.Rows.Remove(row);
                                    break;
                                }
                            }
                            checkedListBox.Items.Add(i, isChecked);
                        }
                        break;

                    case DisplayLevel.BY_REGIONS:
                        DataTable regionsDataTable = Utilities.GetAllRegions();
                        DataTable selectedRegions = Utilities.GetAutoReminderConfiguredRegions();
                        foreach (DataRow r in regionsDataTable.Rows)
                        {
                            int regionId = int.Parse(r["RegionID"].ToString());
                            ListItem i = new ListItem();
                            i.Text = r["RegionName"].ToString();
                            i.Value = regionId;

                            bool isChecked = false;
                            foreach (DataRow row in selectedRegions.Rows)
                            {
                                int id = int.Parse(row["RegionId"].ToString());
                                if (id == regionId)
                                {
                                    isChecked = true;
                                    selectedRegions.Rows.Remove(row);
                                    break;
                                }
                            }
                            checkedListBox.Items.Add(i, isChecked);
                        }
                        break;
                }
            }
        }

        private void lklListSelectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (int i = 0; i < checkedListBox.Items.Count; i++)
            {
                checkedListBox.SetItemChecked(i, true);
            }
        }

        private void lklListUnselectAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (int i = 0; i < checkedListBox.Items.Count; i++)
            {
                checkedListBox.SetItemChecked(i, false);
            }
        }

        private void chbEnableAutoReminder_CheckedChanged(object sender, EventArgs e)
        {
            gboTemplateAndReceivers.Enabled = chbEnableAutoReminder.Checked;
            gboSendingPattern.Enabled = chbEnableAutoReminder.Checked;
        }

        private void lklSelectTargetUsers_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var editor = new SelectTargetSMSReceivers();
            editor.ShowDialog(this);
        }

        private void rdoReceiverSelectedUsers_CheckedChanged(object sender, EventArgs e)
        {
            lklSelectTargetUsers.Enabled = rdoReceiverSelectedUsers.Checked;
        }

        private void rdoTemplateEachReport_CheckedChanged(object sender, EventArgs e)
        {
            lklEachReportTemplate.Enabled = rdoTemplateEachReport.Checked;
        }

        private void chbExcludeHolidays_CheckedChanged(object sender, EventArgs e)
        {
            lklSetHolidays.Enabled = chbExcludeHolidays.Checked;
        }

        private void chbUseWorkingHours_CheckedChanged(object sender, EventArgs e)
        {
            //lklSetWorkingHours.Enabled = chbUseWorkingHours.Checked;
            timePickerWorkStart.Visible = chbUseWorkingHours.Checked;
            lblWorkingHoursTo.Visible = chbUseWorkingHours.Checked;
            timePickerWorkEnd.Visible = chbUseWorkingHours.Checked;
        }

        private void lklSetHolidays_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var editor = new SetHolidays();
            editor.ShowDialog(this);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            gboTemplateAndReceivers.Enabled = false;
            gboSendingPattern.Enabled = false;
            panelButtons.Enabled = false;
            string saveButtonText = btnSave.Text;
            btnSave.Text = "Please wait...";
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();

            try
            {

                bool autoReminderEnabled = chbEnableAutoReminder.Checked;
                Utilities.SetSetting(AutoReminderSettings.ENABLE_AUTO_SMS_REMINDERS, autoReminderEnabled);

                AutoReminderConfiguration configuration = AutoReminderConfiguration.DEFAULT;
                #region Message Template
                if (rdoTemplateAllReports.Checked)
                {
                    configuration |= AutoReminderConfiguration.MESSAGE_TEMPLATE_SAME_ALL_REPORTS;
                }

                // This needs to be saved separately because we need it in other settings
                string template = txtTemplateAllReports.Text;
                Utilities.SetSetting(AutoReminderSettings.MESSAGE_TEMPLATE, template);

                if (rdoTemplateEachReport.Checked)
                {
                    configuration |= AutoReminderConfiguration.MESSAGE_TEMPLATE_EACH_REPORT_HAS_ITS_TEMPLATE;
                }
                #endregion

                #region Receivers of Reminders
                if (rdoReceiverRegisteredUsers.Checked)
                {
                    configuration |= AutoReminderConfiguration.REMINDER_RECEIVERS_ALL_REGISTERED;
                }

                if (rdoReceiverSelectedUsers.Checked)
                {
                    configuration |= AutoReminderConfiguration.REMINDER_RECEIVERS_SELECTED_USERS;
                }

                if (rdoReceiverLastReportSender.Checked)
                {
                    configuration |= AutoReminderConfiguration.REMINDER_RECEIVERS_LAST_REPORT_SENDER;
                }
                #endregion

                #region Reminding Facilities
                ListItem selectedItem = cboDisplayLevel.SelectedItem as ListItem;
                if (selectedItem != null)
                {
                    DisplayLevel displayLevel = (DisplayLevel)selectedItem.Value;
                    switch (displayLevel)
                    {
                        case DisplayLevel.BY_FACILITIES:
                            var selectedFacilities = new List<string>();
                            foreach (var i in checkedListBox.CheckedItems)
                            {
                                ListItem item = (ListItem)i;
                                string facilityCode = item.Value.ToString();
                                selectedFacilities.Add(facilityCode);
                            }
                            Utilities.SaveAutoReminderFacilities(selectedFacilities);
                            configuration |= AutoReminderConfiguration.REMINDED_FACILITIES_BY_FACILITIES;
                            break;

                        case DisplayLevel.BY_DISTRICTS:
                            var selectedDistricts = new List<int>();
                            foreach (var i in checkedListBox.CheckedItems)
                            {
                                ListItem item = (ListItem)i;
                                int districtId = int.Parse(item.Value.ToString());
                                selectedDistricts.Add(districtId);
                            }
                            Utilities.SaveAutoReminderDistricts(selectedDistricts);
                            configuration |= AutoReminderConfiguration.REMINDED_FACILITIES_BY_DISTRICTS;
                            break;

                        case DisplayLevel.BY_REGIONS:
                            var selectedRegions = new List<int>();
                            foreach (var i in checkedListBox.CheckedItems)
                            {
                                ListItem item = (ListItem)i;
                                int regionId = int.Parse(item.Value.ToString());
                                selectedRegions.Add(regionId);
                            }
                            Utilities.SaveAutoReminderRegions(selectedRegions);
                            configuration |= AutoReminderConfiguration.REMINDED_FACILITIES_BY_REGIONS;
                            break;
                    }
                }
                #endregion

                #region Trigger and Repetition
                decimal daysBeforeReminding = numericUpDownDaysBeforeSending.Value;
                int iDaysBeforeReminding = Convert.ToInt32(daysBeforeReminding);
                Utilities.SetSetting(AutoReminderSettings.TRIGGER_DAYS_BEFORE_REMINDING, iDaysBeforeReminding);

                if (rdoRepetitionMonthly.Checked)
                {
                    configuration |= AutoReminderConfiguration.REPETITION_PATTERN_MONTHLY;
                }

                if (rdoRepetitionWeekly.Checked)
                {
                    configuration |= AutoReminderConfiguration.REPETITION_PATTERN_WEEKLY;
                }
                #endregion

                #region Stopping Condition
                if (rdoStopUntilReceived.Checked)
                {
                    configuration |= AutoReminderConfiguration.STOPPING_CONDITION_UNTIL_REPORT_RECEIVED;
                }

                if (rdoStopAfterTwoAttempts.Checked)
                {
                    configuration |= AutoReminderConfiguration.STOPPING_CONDITION_AFTER_TWO_ATTEMPTS;
                }

                if (rdoStopUntilMonthEnd.Checked)
                {
                    configuration |= AutoReminderConfiguration.STOPPING_CONDITION_UNTILL_END_OF_MONTH;
                }
                #endregion

                #region Sending Exception
                if (chbExcludeWeekends.Checked)
                {
                    configuration |= AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_WEEK_ENDS;
                }

                if (chbExcludeHolidays.Checked)
                {
                    configuration |= AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_HOLIDAYS;
                }

                if (chbUseWorkingHours.Checked)
                {
                    configuration |= AutoReminderConfiguration.SENDING_EXCEPTION_USE_WORKING_HOURS;
                    string startWorkingHours = timePickerWorkStart.Value.ToString("s");
                    string endWorkingHours = timePickerWorkEnd.Value.ToString("s");

                    Utilities.SetSetting(AutoReminderSettings.SENDING_EXCEPTION_START_WORKING, startWorkingHours);
                    Utilities.SetSetting(AutoReminderSettings.SENDING_EXCEPTION_END_WORKING, endWorkingHours);
                }
                #endregion

                #region One Reminder Per Facility
                if (chbSendOneReminderPerFacility.Checked)
                {
                    configuration |= AutoReminderConfiguration.MESSAGE_TEMPLATE_ONE_REMINDER_PER_FACILITY;
                    decimal limit = numericUpDownSingleReminderLimit.Value;
                    Utilities.SetSetting(AutoReminderSettings.MESSAGE_TEMPLATE_ONE_REMINDER_PER_FACILITY, limit);
                }
                #endregion

                int iConfiguration = (int)configuration;
                Utilities.SetSetting(AutoReminderSettings.AUTO_REMINDER_BASIC_INFO, iConfiguration);
                string saveDate = DateTime.Now.ToString("s");
                Utilities.SetSetting(AutoReminderSettings.AUTO_REMINDER_SETTING_SAVE_DATE, saveDate);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                gboTemplateAndReceivers.Enabled = true;
                gboSendingPattern.Enabled = true;
                panelButtons.Enabled = true;
                btnSave.Text = saveButtonText;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            LoadAutoReminderConfigurations();
        }

        private void chbSendOneReminderPerFacility_CheckedChanged(object sender, EventArgs e)
        {
            numericUpDownSingleReminderLimit.Enabled = chbSendOneReminderPerFacility.Checked;
        }

        #region Private Helper Methods
        private void CreateDisplayLevelList()
        {
            var displayLevels = new List<ListItem>();

            ListItem item = new ListItem();
            item.Text = BY_FACILITIES;
            item.Value = DisplayLevel.BY_FACILITIES;
            displayLevels.Add(item);

            item = new ListItem();
            item.Text = BY_DISTRICTS;
            item.Value = DisplayLevel.BY_DISTRICTS;
            displayLevels.Add(item);

            item = new ListItem();
            item.Text = BY_REGIONS;
            item.Value = DisplayLevel.BY_REGIONS;
            displayLevels.Add(item);

            cboDisplayLevel.DataSource = displayLevels;
        }

        #region Loading Automatic SMS Reminders
        private void LoadAutoReminderConfigurations()
        {
            string sEnabled = Utilities.GetSetting(AutoReminderSettings.ENABLE_AUTO_SMS_REMINDERS);
            bool enabled = false;
            bool.TryParse(sEnabled, out enabled);
            chbEnableAutoReminder.Checked = enabled;

            string sAutoReminderBasicInfo = Utilities.GetSetting(AutoReminderSettings.AUTO_REMINDER_BASIC_INFO);
            int autoReminderBasicInfo = 0;
            if (int.TryParse(sAutoReminderBasicInfo, out autoReminderBasicInfo))
            {
                AutoReminderConfiguration autoReminderConfig = (AutoReminderConfiguration)autoReminderBasicInfo;
                ConfigureMessageTemplate(autoReminderConfig);
                ConfigureReminderReceivers(autoReminderConfig);
                ConfigureRemindingFacilities(autoReminderConfig);
                ConfigureTriggersAndRepetition(autoReminderConfig);
                ConfigureStoppingCondition(autoReminderConfig);
                ConfigureSendingException(autoReminderConfig);
                ConfigureOneReminderPerFacility(autoReminderConfig);
            }
        }

        private void ConfigureMessageTemplate(AutoReminderConfiguration autoReminderConfig)
        {
            if (AutoReminderConfiguration.MESSAGE_TEMPLATE_SAME_ALL_REPORTS ==
                (autoReminderConfig & AutoReminderConfiguration.MESSAGE_TEMPLATE_SAME_ALL_REPORTS))
            {
                rdoTemplateAllReports.Checked = true;
            }

            string messageTemplate = Utilities.GetSetting(AutoReminderSettings.MESSAGE_TEMPLATE);
            txtTemplateAllReports.Text = messageTemplate;

            if (AutoReminderConfiguration.MESSAGE_TEMPLATE_EACH_REPORT_HAS_ITS_TEMPLATE ==
                (autoReminderConfig & AutoReminderConfiguration.MESSAGE_TEMPLATE_EACH_REPORT_HAS_ITS_TEMPLATE))
            {
                rdoTemplateEachReport.Checked = true;
            }

            List<string> reportMessageTemplates = new List<string>();
            DataTable reports = Utilities.GetAllExpectedReports();
            DataTable autoReminderReportMessageTemplates = Utilities.GetAutoReminderReportMessageTemplates();
            foreach (DataRow r in autoReminderReportMessageTemplates.Rows)
            {
                bool enabled = bool.Parse(r["EnableAutoReminder"].ToString());
                if (enabled)
                {
                    int reportId = int.Parse(r["ReportId"].ToString());
                    string reportName = string.Empty;

                    foreach (DataRow row in reports.Rows)
                    {
                        int repId = int.Parse(row["RepID"].ToString());
                        if (reportId == repId)
                        {
                            reportName = row["ReportName"].ToString();
                            break;
                        }
                    }

                    string template = r["MessageTemplate"].ToString();
                    string displayText = String.Format("{0} - {1}", reportName, template);
                    reportMessageTemplates.Add(displayText);
                }
            }
            DisplayTemplatesInRichText(rtxtTemplateEachReport, reportMessageTemplates);
        }

        private void ConfigureReminderReceivers(AutoReminderConfiguration autoReminderConfig)
        {
            if (AutoReminderConfiguration.REMINDER_RECEIVERS_ALL_REGISTERED ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDER_RECEIVERS_ALL_REGISTERED))
            {
                rdoReceiverRegisteredUsers.Checked = true;
            }

            if (AutoReminderConfiguration.REMINDER_RECEIVERS_SELECTED_USERS ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDER_RECEIVERS_SELECTED_USERS))
            {
                rdoReceiverSelectedUsers.Checked = true;
            }

            if (AutoReminderConfiguration.REMINDER_RECEIVERS_LAST_REPORT_SENDER ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDER_RECEIVERS_LAST_REPORT_SENDER))
            {
                rdoReceiverLastReportSender.Checked = true;
            }
        }

        private void ConfigureRemindingFacilities(AutoReminderConfiguration autoReminderConfig)
        {
            DisplayLevel displayLevel = DisplayLevel.BY_FACILITIES;
            if (AutoReminderConfiguration.REMINDED_FACILITIES_BY_FACILITIES ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDED_FACILITIES_BY_FACILITIES))
            {
                displayLevel = DisplayLevel.BY_FACILITIES;
            }

            if (AutoReminderConfiguration.REMINDED_FACILITIES_BY_DISTRICTS ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDED_FACILITIES_BY_DISTRICTS))
            {
                displayLevel = DisplayLevel.BY_DISTRICTS;
            }

            if (AutoReminderConfiguration.REMINDED_FACILITIES_BY_REGIONS ==
                (autoReminderConfig & AutoReminderConfiguration.REMINDED_FACILITIES_BY_REGIONS))
            {
                displayLevel = DisplayLevel.BY_REGIONS;
            }

            foreach (var item in cboDisplayLevel.Items)
            {
                ListItem i = item as ListItem;
                if (i != null)
                {
                    DisplayLevel iDisplayLevel = (DisplayLevel)i.Value;
                    if (displayLevel == iDisplayLevel)
                    {
                        cboDisplayLevel.Text = i.Text;
                        break;
                    }
                }
            }
        }

        private void ConfigureTriggersAndRepetition(AutoReminderConfiguration autoReminderConfig)
        {
            string sDaysBeforeReminding = Utilities.GetSetting(AutoReminderSettings.TRIGGER_DAYS_BEFORE_REMINDING);
            decimal daysBeforeReminding = AutoReminderSettings.DEFAULT_DAYS_BEFORE_REMINDING;
            decimal.TryParse(sDaysBeforeReminding, out daysBeforeReminding);
            numericUpDownDaysBeforeSending.Value = daysBeforeReminding;

            if (AutoReminderConfiguration.REPETITION_PATTERN_WEEKLY ==
                (autoReminderConfig & AutoReminderConfiguration.REPETITION_PATTERN_WEEKLY))
            {
                rdoRepetitionWeekly.Checked = true;
            }

            if (AutoReminderConfiguration.REPETITION_PATTERN_MONTHLY ==
                (autoReminderConfig & AutoReminderConfiguration.REPETITION_PATTERN_MONTHLY))
            {
                rdoRepetitionMonthly.Checked = true;
            }
        }

        private void ConfigureStoppingCondition(AutoReminderConfiguration autoReminderConfig)
        {
            if (AutoReminderConfiguration.STOPPING_CONDITION_UNTIL_REPORT_RECEIVED ==
                (autoReminderConfig & AutoReminderConfiguration.STOPPING_CONDITION_UNTIL_REPORT_RECEIVED))
            {
                rdoStopUntilReceived.Checked = true;
            }

            if (AutoReminderConfiguration.STOPPING_CONDITION_AFTER_TWO_ATTEMPTS ==
                (autoReminderConfig & AutoReminderConfiguration.STOPPING_CONDITION_AFTER_TWO_ATTEMPTS))
            {
                rdoStopAfterTwoAttempts.Checked = true;
            }

            if (AutoReminderConfiguration.STOPPING_CONDITION_UNTILL_END_OF_MONTH ==
                (autoReminderConfig & AutoReminderConfiguration.STOPPING_CONDITION_UNTILL_END_OF_MONTH))
            {
                rdoStopUntilMonthEnd.Checked = true;
            }
        }

        private void ConfigureSendingException(AutoReminderConfiguration autoReminderConfig)
        {
            if (AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_WEEK_ENDS ==
                (autoReminderConfig & AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_WEEK_ENDS))
            {
                chbExcludeWeekends.Checked = true;
            }

            if (AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_HOLIDAYS ==
                (autoReminderConfig & AutoReminderConfiguration.SENDING_EXCEPTION_EXCLUDE_HOLIDAYS))
            {
                chbExcludeHolidays.Checked = true;
            }

            if (AutoReminderConfiguration.SENDING_EXCEPTION_USE_WORKING_HOURS ==
                (autoReminderConfig & AutoReminderConfiguration.SENDING_EXCEPTION_USE_WORKING_HOURS))
            {
                chbUseWorkingHours.Checked = true;
            }

            string startWorkingHours = Utilities.GetSetting(AutoReminderSettings.SENDING_EXCEPTION_START_WORKING);
            DateTime startHour = DateTime.Parse(startWorkingHours);
            timePickerWorkStart.Value = startHour;

            string endWorkingHours = Utilities.GetSetting(AutoReminderSettings.SENDING_EXCEPTION_END_WORKING);
            DateTime endHour = DateTime.Parse(endWorkingHours);
            timePickerWorkEnd.Value = endHour;
        }

        private void ConfigureOneReminderPerFacility(AutoReminderConfiguration autoReminderConfig)
        {
            string sLimit = Utilities.GetSetting(AutoReminderSettings.MESSAGE_TEMPLATE_ONE_REMINDER_PER_FACILITY);
            decimal limit = AutoReminderSettings.DEFAULT_REPORT_NUMBER_BEFORE_SINGLE_REMINDER;
            decimal.TryParse(sLimit, out limit);
            numericUpDownSingleReminderLimit.Value = limit;

            if (AutoReminderConfiguration.MESSAGE_TEMPLATE_ONE_REMINDER_PER_FACILITY ==
                (autoReminderConfig & AutoReminderConfiguration.MESSAGE_TEMPLATE_ONE_REMINDER_PER_FACILITY))
            {
                chbSendOneReminderPerFacility.Checked = true;
                numericUpDownSingleReminderLimit.Enabled = chbSendOneReminderPerFacility.Checked;
            }
        }
        #endregion        

        private void lklEachReportTemplate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var editor = new SetReportMesssageTemplates();            
            DialogResult response = editor.ShowDialog(this);
            
            if (response == System.Windows.Forms.DialogResult.OK)
            {
                List<string> displayList = editor.EnabledReportsAndTemplates;
                DisplayTemplatesInRichText(rtxtTemplateEachReport, displayList);
            }
        }

        private void DisplayTemplatesInRichText(RichTextBox richTextBox, List<string> displayList)
        {
            // Clear all text from the RichTextBox.
            richTextBox.Clear();

            // Set the font for the opening text to a larger Arial font;
            //richTextBox.SelectionFont = new Font("Arial", 16);

            // Assign the introduction text to the RichTextBox control.
            //richTextBox.SelectedText = "The following is a list of bulleted items:" + "\n";

            // Set the Font for the first item to a smaller size Arial font.
            //richTextBox.SelectionFont = new Font("Arial", 12);

            // Specify that the following items are to be added to a bulled list.
            richTextBox.SelectionBullet = true;

            foreach (var t in displayList)
            {
                richTextBox.SelectedText = t + "\n";
            }

            // Set the color of the item text.
            //richTextBox.SelectionColor = Color.Red;

            // Assign the text to the bulleted item.
            //richTextBox.SelectedText = "Apples" + "\n";

            // Apply same font since font settings do not carry to next line.
            //richTextBox.SelectionFont = new Font("Arial", 12);
            //richTextBox.SelectionColor = Color.Orange;
            //richTextBox.SelectedText = "Oranges" + "\n";

            //richTextBox.SelectionFont = new Font("Arial", 12);
            //richTextBox.SelectionColor = Color.Purple;
            //richTextBox.SelectedText = "Grapes" + "\n";

            // End the bulleted list.
            richTextBox.SelectionBullet = false;

            // Specify the font size and string for text displayed below bulleted list.
            //richTextBox.SelectionFont = new Font("Arial", 16);
            //richTextBox.SelectedText = "Bulleted Text Completed!";
        }


        #endregion
    }
}
